const express = require('express');
const router = express.Router();
const { loginModel } = require("../db/module");
const jwt = require("jsonwebtoken");
const fs = require('fs');
const path = require('path');
const nodemailer = require('nodemailer');
const crypto = require('crypto');
const cors = require('cors');
const bcrypt = require('bcryptjs');

router.use(cors({
  origin: '*', 
  methods: ['GET', 'POST', 'PUT', 'DELETE'], 
  allowedHeaders: ['Content-Type', 'Authorization'] 
}));

router.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

//登录
router.post('/login', async function (req, res, next) {
  let { email, password } = req.body
  let data = await loginModel.findOne({ email, password })
  let token = jwt.sign({ email }, '123')
  if (data) {
    res.send({
      code: 200,
      msg: "登陆成功",
      token
    })
  } else {
    res.send({
      code: 201,
      msg: '账号或密码错误'
    })
  }
});

// 修改密码接口 - 根据email字段更新密码
router.post('/update-password', async (req, res) => {
  try {
      // 这里将password改为newPassword，与前端传递的参数名一致
      const { email, newPassword, sex, kg ,img,name } = req.body; 
      const updateFields = {};
      if (newPassword) updateFields.password = newPassword;
      if (sex) updateFields.sex = sex;
      if (kg) updateFields.kg = kg;
      if (img) updateFields.img = img;
      if (email) updateFields.email = email;
      if (name) updateFields.name = name;

      const updatedUser = await loginModel.findOneAndUpdate(
          { email },
          { $set: updateFields },
          { new: true }
      );

      if (!updatedUser) {
          return res.send({
              code: 404,
              msg: '未找到对应的用户'
          });
      }

      const responseData = {
          code: 200,
          msg: '用户信息更新成功',
          data: {
              email: updatedUser.email,
              password: updatedUser.password,
              sex: updatedUser.sex,
              kg: updatedUser.kg,
              img:updatedUser.img,
              name:updatedUser.name
          }
      };

      let hasOtherUpdates = false;
      if (newPassword) {
          responseData.msg = '密码修改成功';
          hasOtherUpdates = true;
      }
      res.send(responseData);
  } catch (error) {
      console.error('修改用户信息错误:', error);
      res.status(500).send({ code: 500, msg: '服务器错误' });
  }
});


// 检查邮箱是否已存在
router.get('/check-email', async (req, res) => {
  try {
    const user = await loginModel.findOne({ email: req.query.email });
    res.send({ 
      code: 200,
      exists: !!user 
    });
  } catch (error) {
    console.error('检查邮箱错误:', error);
    res.status(500).send({ code: 500, msg: '服务器错误' });
  }
});

// 注册新用户
router.post('/register', async (req, res) => {
  try {
      const { email, verificationCode, password } = req.body;

      // 1. 验证验证码有效性（这里需要实现验证码验证逻辑）
      // const isCodeValid = await verifyCode(email, verificationCode);
      // if (!isCodeValid) {
      //     return res.status(400).send({ code: 400, msg: '验证码无效或已过期' });
      // }

      // 2. 检查邮箱是否已存在（双重检查）
      const existingUser = await loginModel.findOne({ email });
      if (existingUser) {
          return res.status(400).send({ code: 400, msg: '该邮箱已注册' });
      }

      // 3. 这里不进行密码加密，直接使用明文密码
      const newUser = await loginModel.create({
          email,
          password,
          createdAt: new Date()
      });

      res.send({
          code: 200,
          msg: '注册成功',
          data: {
              email: newUser.email,
              password: newUser.password, // 返回明文密码（存在安全风险）
              createdAt: newUser.createdAt
          }
      });

  } catch (error) {
      console.error('注册错误:', error);
      res.status(500).send({ code: 500, msg: '服务器错误' });
  }
});

//渲染
router.get('/getlogin', async (req, res) => {
  let data = await loginModel.find()
  res.send({
    data,
  })
});





/* ============== 邮箱验证码相关功能 ============== */
const EMAIL_USER = process.env.EMAIL_USER || '1514992092@qq.com'; // 发件人邮箱
const EMAIL_PASS = process.env.EMAIL_PASS || 'xsfiuqyjdfrshagi'; // 邮箱授权码
// 创建邮件传输器
const transporter = nodemailer.createTransport({
  host: 'smtp.qq.com',
  port: 465,
  secure: true,
  auth: {
    user: EMAIL_USER,
    pass: EMAIL_PASS
  },
  logger: true,
  debug: true
});

// 新增：获取视频列表接口
router.get('/api/video-list', (req, res) => {
  const dataPath = path.join(__dirname, '../db/data.json');
  fs.readFile(dataPath, 'utf-8', (err, data) => {
    if (err) return res.status(500).json({ error: '读取数据失败' });
    const jsonData = JSON.parse(data);
    const { type } = req.query;
    if (type) {
      // 按分类筛选
      const filtered = jsonData.list.filter(item => String(item.type) === String(type));
      res.json(filtered);
    } else {
      // 返回全部
      res.json(jsonData.list);
    }
  });
});

// 点赞/取消点赞
router.patch('/api/video-list/:id', (req, res) => {
  const dataPath = path.join(__dirname, '../db/data.json');
  fs.readFile(dataPath, 'utf-8', (err, data) => {
    if (err) return res.status(500).json({ error: '读取数据失败' });
    let jsonData = JSON.parse(data);
    const idx = jsonData.list.findIndex(item => String(item.id) === String(req.params.id));
    if (idx === -1) return res.status(404).json({ error: '未找到视频' });
    // 更新 state
    jsonData.list[idx].state = req.body.state;
    fs.writeFile(dataPath, JSON.stringify(jsonData, null, 2), err2 => {
      if (err2) return res.status(500).json({ error: '写入数据失败' });
      res.json(jsonData.list[idx]);
    });
  });
});

// 新增评论
router.post('/api/video-list/:id/comment', (req, res) => {
  const dataPath = path.join(__dirname, '../db/data.json');
  fs.readFile(dataPath, 'utf-8', (err, data) => {
    if (err) return res.status(500).json({ error: '读取数据失败' });
    let jsonData = JSON.parse(data);
    const idx = jsonData.list.findIndex(item => String(item.id) === String(req.params.id));
    if (idx === -1) return res.status(404).json({ error: '未找到视频' });
    if (!jsonData.list[idx].comments) jsonData.list[idx].comments = [];
    // 为评论添加点赞数，初始为0
    const commentWithLikes = {
      ...req.body,
      likes: 0, // 初始为0
      isLiked: false // 默认未点赞
    };
    jsonData.list[idx].comments.unshift(commentWithLikes);
    fs.writeFile(dataPath, JSON.stringify(jsonData, null, 2), err2 => {
      if (err2) return res.status(500).json({ error: '写入数据失败' });
      res.json(jsonData.list[idx].comments);
    });
  });
});

// 评论点赞/取消点赞
router.patch('/api/video-list/:id/comment/:commentIndex/like', (req, res) => {
  const dataPath = path.join(__dirname, '../db/data.json');
  fs.readFile(dataPath, 'utf-8', (err, data) => {
    if (err) return res.status(500).json({ error: '读取数据失败' });
    let jsonData = JSON.parse(data);
    const videoIdx = jsonData.list.findIndex(item => String(item.id) === String(req.params.id));
    if (videoIdx === -1) return res.status(404).json({ error: '未找到视频' });
    
    const commentIdx = parseInt(req.params.commentIndex);
    if (!jsonData.list[videoIdx].comments || !jsonData.list[videoIdx].comments[commentIdx]) {
      return res.status(404).json({ error: '未找到评论' });
    }
    
    const comment = jsonData.list[videoIdx].comments[commentIdx];
    
    // 确保评论有likes字段，如果没有则设置随机数
    if (typeof comment.likes !== 'number') {
      comment.likes = Math.floor(Math.random() * 50) + 1;
    }
    
    // 确保评论有isLiked字段
    if (typeof comment.isLiked !== 'boolean') {
      comment.isLiked = false;
    }
    
    comment.isLiked = !comment.isLiked; // 切换点赞状态
    comment.likes = comment.isLiked ? comment.likes + 1 : Math.max(0, comment.likes - 1); // 更新点赞数，确保不为负数
    
    fs.writeFile(dataPath, JSON.stringify(jsonData, null, 2), err2 => {
      if (err2) return res.status(500).json({ error: '写入数据失败' });
      res.json(comment);
    });
  });
});

// 收藏/取消收藏（gz字段，1=已收藏，0=未收藏）
router.patch('/api/video-list/:id/like', (req, res) => {
  const dataPath = path.join(__dirname, '../db/data.json');
  fs.readFile(dataPath, 'utf-8', (err, data) => {
    if (err) return res.status(500).json({ error: '读取数据失败' });
    let jsonData = JSON.parse(data);
    const idx = jsonData.list.findIndex(item => String(item.id) === String(req.params.id));
    if (idx === -1) return res.status(404).json({ error: '未找到视频' });
    const video = jsonData.list[idx];
    // 切换gz字段
    video.gz = video.gz === '1' ? '0' : '1';
    fs.writeFile(dataPath, JSON.stringify(jsonData, null, 2), err2 => {
      if (err2) return res.status(500).json({ error: '写入数据失败' });
      res.json({ gz: video.gz });
    });
  });
});

module.exports = router;
console.log('SMTP配置验证:', {
  user: EMAIL_USER ? '已设置: ' + EMAIL_USER : '未设置',
  pass: EMAIL_PASS ? '已设置' : '未设置'
});

const verificationCodes = new Map();
const resetTokens = new Map();

// 发送邮箱验证码接口
router.post('/send-login-code', async (req, res) => {
  try {
    // 从请求体获取邮箱
    const { email } = req.body;
    // 验证邮箱格式
    if (!email || !/^\S+@\S+\.\S+$/.test(email)) {
      return res.status(400).json({ code: 400, message: '邮箱格式不正确' });
    }
    // 随机验证码
    const code = Math.floor(100000 + Math.random() * 900000);
    // 设置验证码有效期
    const expiresAt = Date.now() + 5 * 60 * 1000;
    // 存储验证码及其有效期
    verificationCodes.set(email, { code, expiresAt });

    // 发送验证码邮件
    const info = await transporter.sendMail({
      from: `"系统管理员" <${EMAIL_USER}>`,
      to: email,
      subject: '登录验证码',
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #eee; border-radius: 8px;">
          <h2 style="color: #1890ff; text-align: center;">花艺与手工DIY</h2>
          <p style="text-align: center; font-size: 16px; margin: 20px 0;">您的登录验证码是：</p>
          <h3 style="color: #333; text-align: center; margin: 10px 0; font-size: 24px;">${code}</h3>
          <p style="text-align: center; color: #666; margin-top: 20px;">有效期5分钟，请勿泄露给他人</p>
        </div>
      `
    });

    console.log('邮件已发送:', info.messageId);
    res.json({ code: 200, message: '验证码已发送' });

  } catch (error) {
    console.error('邮件发送失败详情:', {
      error: error.message,
      stack: error.stack,
      config: {
        EMAIL_USER: EMAIL_USER,
        EMAIL_PASS: EMAIL_PASS ? '******' : '未设置'
      }
    });

    // 格式化错误信息
    let errorMessage = '发送验证码失败';
    if (error.message.includes('Invalid login')) {
      errorMessage = '邮箱账号或授权码错误，请检查SMTP配置';
    } else if (error.message.includes('Connection timeout')) {
      errorMessage = '连接SMTP服务器超时，请检查网络连接';
    } else if (error.message.includes('550')) {
      errorMessage = '邮箱服务拒绝发送，请检查邮箱设置';
    }

    res.status(500).json({
      code: 500,
      message: errorMessage,
      detail: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

//  验证邮箱验证码接口
router.post('/verify-code', (req, res) => {
  try {
    // 从请求体获取邮箱和验证码
    const { email, code } = req.body;
    console.log('收到验证请求:', { email, code });

    // 验证参数完整性
    if (!email || !code) {
      console.log('验证失败: 参数不完整', { email, code });
      return res.status(400).json({ code: 400, message: '参数不完整' });
    }

    // 获取存储的验证码记录
    const record = verificationCodes.get(email);
    console.log('验证码记录:', record);

    // 验证验证码是否存在
    if (!record) {
      console.log('验证失败: 未找到验证码记录', { email });
      return res.status(400).json({ code: 400, message: '请先获取验证码' });
    }

    // 验证验证码是否过期
    if (record.expiresAt < Date.now()) {
      console.log('验证失败: 验证码过期', { email, expiresAt: record.expiresAt });
      verificationCodes.delete(email); // 移除过期验证码
      return res.status(400).json({ code: 400, message: '验证码已过期' });
    }

    // 验证验证码是否正确
    if (parseInt(code) !== record.code) {
      console.log('验证失败: 验证码不匹配', { provided: parseInt(code), expected: record.code });
      return res.status(400).json({ code: 400, message: '验证码错误' });
    }

    // 生成临时登录令牌
    const token = crypto.randomBytes(32).toString('hex');
    // 存储令牌并关联邮箱
    resetTokens.set(token, email);
    // 移除已验证的验证码
    verificationCodes.delete(email);

    res.json({ code: 200, message: '验证成功', data: { token } });

  } catch (error) {
    console.error('验证码验证错误:', error);
    res.status(500).json({ code: 500, message: '服务器错误' });
  }
});

// 后端路由示例
router.post('/alipay/create', async (req, res) => {
  const { orderId, amount } = req.body;
  
  // 调用支付宝API创建支付订单
  const result = await alipaySdk.pageExecute('alipay.trade.page.pay', {
    bizContent: {
      out_trade_no: orderId,
      total_amount: amount,
      subject: '商品支付',
      product_code: 'FAST_INSTANT_TRADE_PAY'
    }
  });
  
  res.json({ code: 200, data: result });
});

module.exports = router;

// 在现有的 router.get('/api/video-list', ...) 路由后面添加

// 获取单个视频详情
router.get('/api/video-list/:id', (req, res) => {
  const dataPath = path.join(__dirname, '../db/data.json');
  fs.readFile(dataPath, 'utf-8', (err, data) => {
    if (err) return res.status(500).json({ error: '读取数据失败' });
    const jsonData = JSON.parse(data);
    const video = jsonData.list.find(item => String(item.id) === String(req.params.id));
    if (!video) {
      return res.status(404).json({ error: '未找到视频' });
    }
    res.json(video);
  });
});
